/**
 * Alipay.com Inc.
 * Copyright (c) 2005-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.core.service.business.impl;

import com.pingan.mobilegw.common.dal.dataobject.MaServiceConfigDO;
import com.pingan.mobilegw.core.model.ServiceConfig;
import com.pingan.mobilegw.core.model.enums.ServiceStatus;
import com.pingan.mobilegw.core.service.business.*;
import com.pingan.mobilegw.core.service.business.descriptor.BusinessProcesserDescriptor;
import com.pingan.mobilegw.core.service.convert.ServiceConfigConvertor;
import com.pingan.mobilegw.core.service.invoke.processor.MobileAdapterProxyProcesser;
import com.pingan.mobilegw.core.service.util.DynamicTimeOutUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务组件
 * 
 * @author lzhe.li
 * @version $Id: BusinessComponentImpl.java, v 0.1 2013-1-11 下午03:07:58 lzhe.li Exp $
 */
@Component("businessComponent")
public class BusinessComponentImpl  implements BusinessComponent {
    /** logger */
    private static final Log logger                = LogFactory.getLog(BusinessComponentImpl.class);

    /** 默认处理器key */
    private static final String                     DEFAULT_PROCESSER     = "default";

    /** 处理器map */
    private static final Map<String, Processor>     processerMap          = new ConcurrentHashMap<String, Processor>();

    /** 服务配置信息map */
    private static final Map<String, ServiceConfig> serviceConfigMap      = new ConcurrentHashMap<String, ServiceConfig>();

    /** 硬编码的服务配置信息map */
    private static final Map<String, ServiceConfig> localServiceConfigMap = new ConcurrentHashMap<String, ServiceConfig>();


    private PinganServiceFactoryManager pinganServiceFactoryManager;


    public void registerExtension(Extension extension) throws Exception {
        Object[] contribs = extension.getContributions();
        if (contribs.length == 0) {
            return;
        }

        synchronized (this) {
            for (Object contrib : contribs) {
                BusinessProcesserDescriptor descriptor = (BusinessProcesserDescriptor) contrib;
                String name = descriptor.getName();
                Processor processer = descriptor.getProcessor();
                processerMap.put(name, processer);
                // 设置配置信息
                ServiceConfig defaultServiceConfig = new ServiceConfig();
                defaultServiceConfig.setOperationType(name);
                defaultServiceConfig.setStatus(ServiceStatus.OPENED);
                defaultServiceConfig.setLocal(true);
                serviceConfigMap.put(name, defaultServiceConfig);
                localServiceConfigMap.put(name, defaultServiceConfig);
            }
        }
    }


    public Processor getProcessor(String operatorType) {
        Processor processor=processerMap.get(operatorType);
        processor = new MobileAdapterProxyProcesser();
        return new GroovyProcessorWrapper(processor);
    }


    public ServiceConfig getServiceConfig(String operatorType) {
        return serviceConfigMap.get(operatorType);
    }


    @Override
    public boolean isLocalService(String operationType) {
        return localServiceConfigMap.containsKey(operationType);
    }


    public synchronized boolean addProcessor(MaServiceConfigDO config) {
        ServiceConfig serviceConfig = ServiceConfigConvertor.convertDoToModel(config);

        if (serviceConfig.getStatus() != ServiceStatus.OPENED) {
            logger.warn("加载服务配置失败！服务状态没有开启，serviceConfig="+serviceConfig);
            return false;
        }

        // 注册sofa的rpc服务
        String[] times = DynamicTimeOutUtil.getTimeOuts(serviceConfig);

        pinganServiceFactoryManager.register(serviceConfig.getSysName(), times);

        processerMap.put(config.getOperationType(), processerMap.get(DEFAULT_PROCESSER));

        serviceConfigMap.put(config.getOperationType(), serviceConfig);

        logger.info("加载服务配置成功！serviceConfig="+serviceConfig);

        return true;
    }


    public synchronized boolean removeProcessor(MaServiceConfigDO config) {
        String operationType = config.getOperationType();
        if (processerMap.get(operationType) != null && serviceConfigMap.get(operationType) != null) {
            processerMap.remove(operationType);
            serviceConfigMap.remove(operationType);
            return true;
        }
        return false;
    }


    public void setPinganServiceFactoryManager(PinganServiceFactoryManager pinganServiceFactoryManager) {
        this.pinganServiceFactoryManager = pinganServiceFactoryManager;
    }

}
